﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MMSWebsite.DataAccessManagement;
using MMSWebsite.Models;

namespace MMSWebsite.Controllers
{
    public class GroupController : Controller
    {
        //
        // GET: /Group/
        readonly MMSEntities _entities = new MMSEntities();
        readonly GroupAccessProvider _groupprovider = new GroupAccessProvider();
        EmployeeAccessProvider _eap = new EmployeeAccessProvider();
        public ActionResult Index()
        {
            var groups = _groupprovider.GetAllGroups();
            return View(groups);
        }

        //
        // GET: /Group/Details/5

        public ActionResult Details(int id)
        {
            return View(_groupprovider.GetGroupById(id));
        }

        //
        // GET: /Group/Create

        public ActionResult Create()
        {
            ViewBag.GroupExistedError = "";
            SetupViewBagAddress(null);
            ViewBag.Reviewers = _eap.GetEmpsByRole("Reviewer")
                                    .Where(c=>c.Employee.Area.CityName == AccountController.EmpAccount.Employee.Area.CityName && c.Employee.IsLocked == false)
                                    .OrderBy(o=>o.Employee.Name)
                                    .Select(x=>x.Employee.Name);
            Group group = new Group();
            return View(group);
        }

        //
        // POST: /Group/Create

        [HttpPost]
        public ActionResult Create(Group group, FormCollection collection)
        {
            //get Area of group
            var area = new GroupArea
                                 {
                                     City = collection.GetValues("CurrentCity").ToList()[0],
                                     Districts = collection.GetValues("CurrentDistrict").ToList()
                                 };
            group.Area = area;
            //get Reviewer
            var responsibility = _eap.GetEmployeeByName(collection.GetValues("Responsibility").ToList()[0]);
            group.Responsibility = responsibility;

            //check validation
            if(ModelState.IsValid)
            {
                if(!_groupprovider.CheckGroupExist(group.GroupName,false))
                {
                    // TODO: Add insert logic here
                    _groupprovider.AddGroup(group);
                    return RedirectToAction("Index");
                }
                else
                {
                    ViewBag.GroupExistedError = "Group name existed! Please try another name.";
                    return View(group);
                }
            }
            else
            {
                return View(group);
            }
        }

        //
        // GET: /Group/Edit/5

        public ActionResult Edit(int id)
        {
            ViewBag.GroupExistedError = "";
            SetupViewBagAddress(id);
            var group = _groupprovider.GetGroupById(id);
            //get emp with role Reviewer for Responsibile Reviewer of this group
            ViewBag.Reviewers = _eap.GetEmpsByRole("Reviewer")
                                    .Where(c => c.Employee.Area.CityName == AccountController.EmpAccount.Employee.Area.CityName && c.Employee.IsLocked == false)
                                    .OrderBy(o => o.Employee.Name)
                                    .Select(x => x.Employee.Name);
            return View(group);
        }

        //
        // POST: /Group/Edit/5

        [HttpPost]
        public ActionResult Edit(Group group, int id, FormCollection collection)
        {
            //get Area from View
            var area = new GroupArea
                           {
                               City = collection.GetValues("CurrentCity").ToList()[0],
                               Districts = collection.GetValues("CurrentDistrict").ToList()
                           };
            group.Area = area;
            //get Reviewer from View
            var responsibility = _eap.GetEmployeeByName(collection.GetValues("Responsibility").ToList()[0]);
            group.Responsibility = responsibility;

            //check Validation
            //if (ModelState.IsValid)
            //{
                if (!_groupprovider.CheckGroupExist(group.GroupName,true))
                {
                    // TODO: Add insert logic here
                    _groupprovider.UpdateGroup(group);
                    return RedirectToAction("Index");
                }
                else
                {
                    ViewBag.GroupExistedError = "Group name existed! Please try another name.";
                    return View(group);
                }
            //}
            //else return View(group);
        }

        public JsonResult DistrictList(string city)
        {
            var items = _entities.MMS_AREAs
                .Where(d => d.CityName == city && d.GroupId == null)
                .OrderBy(x => x.DistrictName)
                .Select(c => new
                                 {
                                     DistrictName = c.DistrictName
                                 });
            return Json(items, JsonRequestBehavior.AllowGet);
        }

        private void SetupViewBagAddress(int? id)//id is idGroup
        {
            //lấy area của group nếu có id truyền vào, null nếu ko
            var area = id != null ? _entities.MMS_AREAs.Where(x => x.GroupId == id).ToList() : null;

            
            //area.count = 0 khi có id, nghĩa là group đó tồn tại nhưng chưa có chia khu vực nào thì lấy tất cả các city và group
            if (id == null || area.Count == 0)
            {
                
                ViewBag.CurrentCity = new List<string>();
                ViewBag.CurrentDistricts = new List<string>();
                ViewBag.Cities = _entities.MMS_AREAs.Select(c => c.CityName).Distinct().ToArray();
                string cascadingCity = ViewBag.Cities[0].ToString();
                //groupid = null -> khu vực đó chưa được phân chia
                ViewBag.Districts =
                        _entities.MMS_AREAs.Where(d => d.CityName == cascadingCity && d.GroupId == null).Select(d => d.DistrictName);
            }
            else
            {
                //lấy tất cả các khu vực thuộc group id

                //lấy ra thành phố trong khuc vực
                var currentcity = area.Select(x => x.CityName).Distinct();
                ViewBag.CurrentCity = currentcity; //lấy ra thành phố thuộc khu vực để gán vào View Bag, sau đó show ra tren dropdownlist CurrentCity của group này

                //lấy ra các quận trong khu vực
                ViewBag.CurrentDistricts = area.Select(x => x.DistrictName).Distinct();// lấy tất cả các Districts đã phân trong group show ra trên dropdownlist CurrentDistrict
                
                //Lấy ra thành phố và quận còn lại trong db (không lấy các area đã đc phân chia)
                ViewBag.Cities =
                    _entities.MMS_AREAs.Where(d => d.CityName != currentcity.FirstOrDefault()).Select(
                        x => x.CityName).Distinct();
                ViewBag.Districts =
                    _entities.MMS_AREAs.Where(d => d.CityName == currentcity.FirstOrDefault() && d.GroupId == null).
                        Select(x => x.DistrictName).Distinct();


            }
        }
    }
}
